/**
 * Created by futu2013-07 on 2017/2/27.
 */
let Police = require( 'koa-police');
let convert = require( 'koa-convert');
let validator = require( 'koa-context-validator').default;

let sessionStrategy = {
    name: 'session',
    authenticate: function *(ctx, scope) {
        let authUser = ctx.session.authUser;
        if (scope === 'visitor') {
            return true;
        }
        if (scope === 'user' && authUser && !authUser.isGuest) {
            return true;
        }

        if (scope === 'user' && (!authUser || authUser.isGuest)) {
            return false;
        }

        return false;
    }
};

/**
 *
 * @param options
 * {
 *    policy: {scope: 'user'}, //选择鉴权策略模式,可选 user, visitor
 *    validate: {              //输入验证,可选
 *     params: Joi.object({
 *       id: Joi.number().required()
 *     })
 *   }
 * }
 * @returns {Function}
 */
module.exports = function (options) {
    let _loop = async function () {

    };
    return async function (ctx, next) {
        ctx.request.isAPI = options.isAPI;
        let policies = [];

        if (options.policy) {
            policies.push(
                Object.assign(
                    {methods:[ctx.method], path: ctx.path, enforce: true},
                    options.policy
                )
            );
        }

        let police = Police({
            defaultStrategies: [sessionStrategy],
            policies: policies
        });

        await convert(police)(ctx, _loop);

        if (options.validate) {
            await validator(options.validate)(ctx, _loop);
        }

        await next();
    };
};
